package org.example;

import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;

public class MyThreadPoolDemo {
    static class MyThreadPool{
        private BlockingQueue<Runnable> queue=new LinkedBlockingQueue<>();
        //通过这个方法，来把任务添加到线程中
        public void submit(Runnable runnable) throws InterruptedException {
            queue.put(runnable);
        }
        //n标识线程池里面有几个线程
        //创建了一个固定数量的线程池
        public MyThreadPool(int n){
            for (int i = 0; i < n; i++){
                Thread t=new Thread(()->{
                    while (true) {
                        try {
                            //取出任务，并执行
                            Runnable runnable=queue.take();
                            runnable.run();
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                });
                t.start();
            }
        }
    }

    public static void main(String[] args) throws InterruptedException {
        MyThreadPool pool=new MyThreadPool(4);
        for (int i = 0; i < 1000; i++){
            pool.submit(new Runnable() {
                @Override
                public void run() {
                    System.out.println(Thread.currentThread().getName()+"正在执行任务");
                }
            });
        }
    }

}
